package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.enums.ContextTypeEnum;
import com.huntmobi.springsecuritydemo.base.enums.TokenEnum;
import com.huntmobi.springsecuritydemo.base.http.Response;
import com.huntmobi.springsecuritydemo.base.pojo.SysUser;
import com.huntmobi.springsecuritydemo.base.util.JwtUtil;
import com.huntmobi.springsecuritydemo.base.vo.SysLoginSuccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @BelongsProject: spring-security-demo
 * @BelongPackage: com.huntmobi.springsecuritydemo.base.filter
 * @Author: zouzhimin
 * @Date: 2020/11/19 11:57
 * @Description: 登录成功处理
 **/
@Component
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType(ContextTypeEnum.JSONUTF8.getContextType());
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(Response.success(sysLoginSuccess(authentication))));
        out.flush();
        out.close();
    }

    /**
     * 自定义返回登录成功数据格式
     */
    private SysLoginSuccess sysLoginSuccess(Authentication authentication) throws JsonProcessingException {
        //登录成功，fan返回的数据格式
        SysLoginSuccess sysLoginSuccess = new SysLoginSuccess();
        //强转登录成功后，重数据库查询到的账号信息
        SysUser sysUser = (SysUser) authentication.getPrincipal();
        //存储多个角色
        List<HashMap<String, String>> roles = new ArrayList<>();
        sysUser.getRoles().forEach(sysRole -> {
            HashMap<String, String> map = new HashMap<>(16);
            map.put("roleName", sysRole.getName());
            map.put("roleDesc", sysRole.getNameZh());
            roles.add(map);
        });
        //设置角色
        sysLoginSuccess.setRoles(roles);
        //设置昵称
        sysLoginSuccess.setNikName(sysUser.getNikName());
        //开始生成token
        String token = jwtUtil.getToken(authentication.getAuthorities(),new ObjectMapper().writeValueAsString(sysLoginSuccess));
        //设置token
        sysLoginSuccess.setToken(TokenEnum.TOKENPREFIX.getMsg()+token);
        return sysLoginSuccess;
    }
}